#include <d3d9.h>
#include <d3dx9.h>
#include <list>
#include "direct3d.h"

int xRes,yRes;





bool D3DInit(HINSTANCE hInstance,int width, int height,bool windowed,
			 bool HAL,IDirect3DDevice9** device,WNDPROC WndProc,LPCSTR name,HWND &hWnd)
{
	WNDCLASS wc;
	wc.style         = CS_HREDRAW | CS_VREDRAW ;
	wc.lpfnWndProc   = WndProc; 
	wc.cbClsExtra    = 0;
	wc.cbWndExtra    = 0;
	wc.hInstance     = hInstance;
	wc.hIcon         = LoadIcon(0, IDI_APPLICATION);
	wc.hCursor       = LoadCursor(0, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
	wc.lpszMenuName  = 0;
	wc.lpszClassName = "MainWindow";
	if( !RegisterClass(&wc) ) 
		return false;
	HWND hwnd = 0;
	hwnd = ::CreateWindow("MainWindow", name, 
								WS_OVERLAPPEDWINDOW,0, 0, width, height,0 , 0 , hInstance, 0); 
	hWnd = hwnd;
	if( !hwnd )
		return false;
	ShowWindow(hwnd, SW_SHOW);
	UpdateWindow(hwnd);

	HRESULT hr = 0;
	IDirect3D9* d3d9 = 0;
    d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
    if( !d3d9 )
		return false;
	D3DDEVTYPE devType = HAL ? D3DDEVTYPE_HAL : D3DDEVTYPE_REF;
	D3DCAPS9 caps;
	d3d9->GetDeviceCaps(D3DADAPTER_DEFAULT, devType, &caps);
	int tNl = 0;
	if( caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT )
		tNl = D3DCREATE_HARDWARE_VERTEXPROCESSING;
	else
		tNl = D3DCREATE_SOFTWARE_VERTEXPROCESSING; 
	D3DPRESENT_PARAMETERS d3dpp;
	d3dpp.BackBufferWidth            = width;
	d3dpp.BackBufferHeight           = height;
	d3dpp.BackBufferFormat           = D3DFMT_UNKNOWN;//D3DFMT_R5G6B5;
	d3dpp.BackBufferCount            = 1;
	d3dpp.MultiSampleType            = D3DMULTISAMPLE_NONE;
	d3dpp.MultiSampleQuality         = 0;
	d3dpp.SwapEffect                 = D3DSWAPEFFECT_DISCARD; 
	d3dpp.hDeviceWindow              = hwnd;
	d3dpp.Windowed                   = windowed;
	d3dpp.EnableAutoDepthStencil     = false;
	d3dpp.AutoDepthStencilFormat     = D3DFMT_D24S8;
	d3dpp.Flags                      = 0;
	d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
	d3dpp.PresentationInterval       = D3DPRESENT_INTERVAL_DEFAULT;
	hr = d3d9->CreateDevice(D3DADAPTER_DEFAULT,devType,hwnd,tNl,&d3dpp,device);
	if( FAILED(hr) )
	{
		d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
		hr = d3d9->CreateDevice(D3DADAPTER_DEFAULT,devType,hwnd,tNl,&d3dpp,device);
		if( FAILED(hr) )
		{
			d3d9->Release(); 
			return false;
		}
	}
	d3d9->Release(); 
	xRes = width;
	yRes = height;
	return true;
}


